package ntd.util.frame.action.iot;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import ntd.action.ActionAbs;
import ntd.action.bo.ActionInfo;
import ntd.action.bo.ActionOutBo;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.data.factory.FactoryData;

import java.sql.SQLException;
import java.util.List;

public class ActionIotDeviceDataFlow extends ActionAbs {

    @Override
    public ActionInfo info() {
        return new ActionInfo("设备数据流量", "iot-device-data-flow", new ActionIotDeviceDataFlow());
    }

    
    @Override
    public ActionOutBo handle() {
        String dataCode = actionInBo.getDataCode();
        if (StrUtil.isBlank(dataCode)) {
            throw new ComException("请传入正确的设备编码...");
        }

        String sql = "SELECT tddi.* from things_device_data tdd INNER JOIN things_device_data_item tddi ON tdd.id = tddi.data_id\n" +
                "WHERE tdd.device_code = ? and tdd.cn = '2061' and tdd.report_time > ? and tddi.factor_code = 'e20101'";

        // 当日月流量
        Double currentMonthFlow = 0d;
        // 当周数据
        Double currentWeekFlow = 0d;
        // 当天数据
        Double currentDayFlow = 0d;
        try {
            // 当日流量
            List<Entity> monthEntityList = FactoryData.db().query(sql, dataCode, DateUtil.beginOfMonth(DateUtil.date()));

            for (Entity entity : monthEntityList) {
                // 当月数据
                currentMonthFlow += ObjectUtil.defaultIfNull(entity.getDouble("factor_val_cou"), 0d);
                // 当周数据
                if (DateUtil.compare(DateUtil.beginOfWeek(DateUtil.date()), entity.getDate("created_date")) <= 0) {
                    currentWeekFlow += ObjectUtil.defaultIfNull(entity.getDouble("factor_val_cou"), 0d);
                }
                // 当天数据
                if (DateUtil.compare(DateUtil.beginOfDay(DateUtil.date()), entity.getDate("created_date")) <= 0) {
                    currentDayFlow += ObjectUtil.defaultIfNull(entity.getDouble("factor_val_cou"), 0d);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        JSONObject res = JSONUtil.createObj();
        res.set("currentDayFlow", NumberUtil.roundStr(currentDayFlow, 4));
        res.set("currentWeekFlow", NumberUtil.roundStr(currentWeekFlow, 4));
        res.set("currentMonthFlow", NumberUtil.roundStr(currentMonthFlow, 4));
        return new ActionOutBo(res);
    }
}
